export default function jsonp(url, params = {}, callbackKey = 'callback') {
  return new Promise((resolve, reject) => {
    const callbackName = `jsonp_${Date.now()}`;
    const script = document.createElement('script'); // 提升到外层作用域

    window[callbackName] = (data) => {
      resolve(data);
      cleanup();
    };

    script.onerror = () => {
      reject(new Error('JSONP 请求失败'));
      cleanup();
    };

    function cleanup() {
      if (script) {
        document.body.removeChild(script);
        delete window[callbackName];
      }
    }

    script.src = `${url}?${Object.keys(params).map(k => `${k}=${encodeURIComponent(params[k])}`).join('&')}&${callbackKey}=${callbackName}`;
    document.body.appendChild(script);
  });
}